<template>
  <el-dialog v-model="visible" title="选择审批人" width="600px">
    <div class="approver-dialog">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="指定人员" name="users">
          <div class="search-box">
            <el-input 
              v-model="userSearch" 
              placeholder="搜索用户"
              clearable
              @input="filterUsers"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <el-table 
            :data="filteredUsers" 
            height="300"
            @selection-change="onUserSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="departmentId" label="部门">
              <template #default="{ row }">
                {{ getDepartmentName(row.departmentId) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="部门负责人" name="departments">
          <el-table 
            :data="departments" 
            height="300"
            @selection-change="onDepartmentSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="部门名称" />
            <el-table-column prop="managerId" label="负责人">
              <template #default="{ row }">
                {{ getManagerName(row.managerId) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="指定角色" name="roles">
          <el-table 
            :data="roles" 
            height="300"
            @selection-change="onRoleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="description" label="描述" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
      
      <div class="selected-approvers">
        <h4>已选择的审批人:</h4>
        <div class="approver-tags">
          <el-tag 
            v-for="approver in selectedApprovers" 
            :key="approver.id"
            closable
            @close="removeApprover(approver)"
          >
            {{ approver.name }}
          </el-tag>
        </div>
      </div>
    </div>
    
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import type { User, Department, Role } from '../../types/workflow'

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [approvers: User[]]
}>()

// 响应式数据
const activeTab = ref('users')
const userSearch = ref('')
const selectedApprovers = ref<User[]>([])
const selectedUsers = ref<User[]>([])
const selectedDepartments = ref<Department[]>([])
const selectedRoles = ref<Role[]>([])

// 模拟数据
const users = ref<User[]>([
  { id: '1', name: '张三', email: 'zhangsan@example.com', departmentId: '1', roles: ['user'] },
  { id: '2', name: '李四', email: 'lisi@example.com', departmentId: '1', roles: ['user'] },
  { id: '3', name: '王五', email: 'wangwu@example.com', departmentId: '2', roles: ['manager'] },
  { id: '4', name: '赵六', email: 'zhaoliu@example.com', departmentId: '2', roles: ['user'] }
])

const departments = ref<Department[]>([
  { id: '1', name: '技术部', managerId: '1' },
  { id: '2', name: '产品部', managerId: '3' },
  { id: '3', name: '运营部', managerId: '2' }
])

const roles = ref<Role[]>([
  { id: '1', name: '管理员', code: 'admin', description: '系统管理员' },
  { id: '2', name: '经理', code: 'manager', description: '部门经理' },
  { id: '3', name: '员工', code: 'user', description: '普通员工' }
])

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const filteredUsers = computed(() => {
  if (!userSearch.value) return users.value
  return users.value.filter(user => 
    user.name.includes(userSearch.value) || 
    user.email.includes(userSearch.value)
  )
})

// 方法
const filterUsers = () => {
  // 搜索功能已通过计算属性实现
}

const onUserSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection
  updateSelectedApprovers()
}

const onDepartmentSelectionChange = (selection: Department[]) => {
  selectedDepartments.value = selection
  updateSelectedApprovers()
}

const onRoleSelectionChange = (selection: Role[]) => {
  selectedRoles.value = selection
  updateSelectedApprovers()
}

const updateSelectedApprovers = () => {
  const approvers: User[] = []
  
  // 添加选中的用户
  approvers.push(...selectedUsers.value)
  
  // 添加部门负责人
  selectedDepartments.value.forEach(dept => {
    const manager = users.value.find(u => u.id === dept.managerId)
    if (manager && !approvers.find(a => a.id === manager.id)) {
      approvers.push(manager)
    }
  })
  
  // 添加角色用户
  selectedRoles.value.forEach(role => {
    const roleUsers = users.value.filter(u => u.roles.includes(role.id))
    roleUsers.forEach(user => {
      if (!approvers.find(a => a.id === user.id)) {
        approvers.push(user)
      }
    })
  })
  
  selectedApprovers.value = approvers
}

const removeApprover = (approver: User) => {
  const index = selectedApprovers.value.findIndex(a => a.id === approver.id)
  if (index > -1) {
    selectedApprovers.value.splice(index, 1)
  }
}

const getDepartmentName = (departmentId: string) => {
  const dept = departments.value.find(d => d.id === departmentId)
  return dept?.name || departmentId
}

const getManagerName = (managerId: string) => {
  const manager = users.value.find(u => u.id === managerId)
  return manager?.name || managerId
}

const handleConfirm = () => {
  emit('confirm', selectedApprovers.value)
  visible.value = false
}

const handleCancel = () => {
  visible.value = false
}

// 监听对话框打开，重置选择
watch(visible, (newVal) => {
  if (newVal) {
    selectedApprovers.value = []
    selectedUsers.value = []
    selectedDepartments.value = []
    selectedRoles.value = []
    userSearch.value = ''
  }
})

defineOptions({
  name: 'ApproverDialog'
})
</script>

<style scoped>
.approver-dialog {
  max-height: 500px;
  overflow: hidden;
}

.search-box {
  margin-bottom: 16px;
}

.selected-approvers {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.selected-approvers h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
}

.approver-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.approver-tags .el-tag {
  margin-bottom: 4px;
}
</style> 